package com.kbbywyclient.presenter;

import android.content.Context;

import com.kbbywyclient.data.entity.WithdrawRecord;
import com.kbbywyclient.data.model.WithdrawRecordModel;
import com.kbbywyclient.presenter.base.BasePresenter;
import com.kbbywyclient.service.ApiService;
import com.kbbywyclient.service.ApiServiceHelper;
import com.kbbywyclient.ui.contarct.WithdrawMoneyContract;
import com.kbbywyclient.util.LogUtil;
import com.kbbywyclient.util.RsaJsonUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/11 11:14.
 */

public class WithdrawRecordPresenter extends BasePresenter implements WithdrawMoneyContract.Presenter {
    public static final int PAGE_START=0;
    public int page=PAGE_START;
    @Inject
    Context mContext;
    @Inject
    ApiService apiService;
    @Inject
    RsaJsonUtil jsonUtil;

    private WithdrawMoneyContract.View view;

    public List<WithdrawRecord> data;
    @Inject
    public WithdrawRecordPresenter(WithdrawMoneyContract.View view){
        this.view=view;
        this.data=new ArrayList<>();
    }

    @Override
    public void loadData(int salesId, int pageNum) {
        jsonUtil.put("salesID",salesId);
        jsonUtil.put("pageNum",pageNum);
        ApiServiceHelper.
                appointThreadNormal(apiService.getWithdrawRecord(jsonUtil.getRsaParams())).
                subscribe(new Subscriber<WithdrawRecordModel>() {
                    @Override
                    public void onCompleted() {
                        view.loadDataComplete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        page--;
                        if(page<PAGE_START){
                            page=PAGE_START;
                        }
                        view.loadDataComplete();
                    }

                    @Override
                    public void onNext(WithdrawRecordModel withdrawRecordModel) {
                        List<WithdrawRecord> temp=withdrawRecordModel.getData();
                        if(temp!=null&&temp.size()>0){
                            //有提现记录
                            if(page==PAGE_START){
                                data.clear();
                            }
                            data.addAll(temp);
                            view.setCanLoadMore(true);
                        }else{
                            //无数据
                            view.setCanLoadMore(false);
                        }
                        view.loadDataSuc(data);
                    }
                });
    }

    @Override
    public void clearData() {
        page=PAGE_START;
        if(data!=null){
            data.clear();
        }
    }
}
